// 1. 导入express
const express = require('express')
// 2. 创建路由
const router = express.Router()

// 导入数据库相关配置
const { getAll, getOne, exec } = require('../db')

// 3. 编写接口
router.get('/', async function (req, res, next) {
  //操作数据库
  let sql = `select * from gg_traffic`
  const data = await exec(sql)
  res.send({
    code: 0,
    message: '获取所用路况成功',
    result: data,
  })
})
// 根据id获取单个路况
router.get('/:traffic_id', async function (req, res, next) {
  const { traffic_id } = req.params
  // 操作数据库
  let sql = `select * from gg_traffic where traffic_id=${traffic_id}`
  const data = await getOne(sql)
  console.log(data)
  res.send({
    code: 0,
    message: '获取路况成功',
    result: {
      data,
    },
  })
})

// 添加路况
router.post('/', async function (req, res, next) {
  const { traffic_path, traffic_road, traffic_vehicleflow } = req.body
  // 操作数据库
  let sql = `insert into gg_traffic(traffic_path,traffic_road,traffic_vehicleflow) values('${traffic_path}','${traffic_vehicleflow}','${traffic_road}')`
  const data = await exec(sql)
  console.log(data)
  res.send({
    code: 0,
    message: '添加路况成功',
    result: {
      id: data.insertId,
      path: traffic_path,
      road: traffic_road,
      vehicleflow: traffic_vehicleflow,
    },
  })
})

// 删除路况
router.delete('/:traffic_id', async function (req, res) {
  const { traffic_id } = req.params
  //操作数据库
  let sql = `delete from gg_traffic where traffic_id = ${traffic_id}`
  const data = await exec(sql)
  res.send({
    code: 0,
    message: '删除路况成功',
  })
})

module.exports = router
